import React, {useEffect, useState} from 'react';
import { Form, Button, DatePicker,Upload,Input, Modal,Row,message, Col,Popconfirm,Select} from 'antd';
import { connect } from 'umi';
import moment from 'moment';
import {UploadOutlined} from '@ant-design/icons';
import {getregularInfo} from '../../service';
import {getUploadUrl} from '@/utils/upload';
import store from 'store2';

const FormItem = Form.Item;
const { TextArea } = Input;

const formLayout = {
  labelCol: { span: 7 },
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];

const AddForm = (props) => {
  const { onSubmit, onCancel, loading,record,visible,currentUser} = props;
  const [form] = Form.useForm();
  const [fileUploadUrls,setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);

  const fileList = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls,res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.response);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  useEffect(() => {
    if(currentUser && record){
      const fieldsValue = store(`personnel-manage-` + record.id);
      if(fieldsValue){
        form.setFieldsValue({...fieldsValue,hiredate:moment(fieldsValue.hiredate),regularDay:moment(fieldsValue.regularDay)});
        let temp = [];
        fieldsValue.urlIds.fileList?.map(item => {temp.push(item.response);});
        setFileUploadUrls(temp);
        uploadedFiles = fieldsValue.urlIds.fileList;
      }else{
        getregularInfo(record.id).then(res => {
          form.setFieldsValue({
            ...res,
            hiredate: res.hiredate ? moment(res.hiredate) : undefined,
            regularDay:record.regularDay ? moment(record.regularDay) : undefined,
            orgname:res.beforeOrgName,
            afterUnitName:record.afterUnitName,
            afterJobName:record.afterJobName,
            beforeJobName:record.beforeJobName,
            beforeUnitName:record.beforeUnitName,
            probationday:record.probationday,
            remark:''
          });
        })
      }
    }
  }, [visible]);

  const onFormCancel = () => {
    form.resetFields();
    onCancel();
    uploadedFiles = [];
    setFileUploadUrls([]);
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    onSubmit({...fieldsValue,id:record.id,urls:fileUploadUrls});
    setFileUploadUrls([]);
    uploadedFiles = [];
  };

  const onFormSave = async () => {
    const fieldsValue = await form.validateFields();
    store(`personnel-manage-` + record.id,fieldsValue);
    message.success("信息暂存成功！");
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="code" label="工号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="name" label="姓名">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="hiredate" label="入职日期">
              <DatePicker disabled={true} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem label={'公司'} name="orgname">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem label={'现任部门'} name="beforeUnitName">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem label={'现任岗位'} name="beforeJobName">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="unitname" label="申请晋升部门">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobname" label="晋升岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="probationday" label="考核期限">
              <Input disabled={true} suffix="个月"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="regularDay" label="转正时间">
              <DatePicker disabled={true} className='widthStyle'/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="urlIds" label="上传附件" rules={[{required: true, message: '附件不能为空'}]}>
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="remark" labelCol={{span: 2}} label="申请说明">
              <TextArea rows={4} className='widthStyle'/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button onClick={() => onFormSave()}>暂存</Button>
        <Popconfirm title="是否发送转正申请？" cancelText='取消' okText='确认' onConfirm={() => handleSubmit()}>
          <Button type="primary" loading={loading}>提交</Button>
        </Popconfirm>
      </>
    )
  }

  return (
    <Modal
      maskClosable={false}
      width={1280}
      destroyOnClose
      centered
      title="管理晋级转正申请"
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}

export default connect(({user}) => ({
  currentUser: user.currentUser,
}))(AddForm)
